package com.hb.umsp.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class MaxNoUtils {

    @Autowired
    RedisTemplate redisTemplate;
    /**
     * 从redis中获取序列号，并+1
     * @param s
     * @param length
     * @return
     */
    public String getIncrement(String type,String s,int length){
        String rst = s;
        int increment = 0;
        RedisConnection conn = null;
        try {
            conn = redisTemplate.getConnectionFactory().getConnection();
            byte[] bytes = conn.get(type.getBytes());
            if (bytes !=null && bytes.length > 0) {
                increment = Integer.parseInt(new String(bytes)) + 1;
            }
            int num = String.valueOf(increment).length();
            String ldap = "0";
            if (num < length) {
                for (int i=1; i<length - num; i++) {
                    ldap += "0";
                }
            }
            rst += ldap + increment;
            conn.set(type.getBytes(),String.valueOf(increment).getBytes());

            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (!conn.isClosed()) {
                conn.close();
            }
        }
        return rst;
    }
}
